<template>
    <view class="body-view">
        <!--导航和状态栏-->
        <view class="state-navigation">
            <view class="slim_header_navigation d-flex a-center j-center">
                <view class="left_box" @tap="goBack">
                    <image src="/static/center/back.png" class="back"></image>
                </view>
                <view class="title">{{ titleText }}</view>
                <view class="right_box">
                    <!-- <text v-if="type==='pick'" @tap="goProgrammeCreate" style="font-size:30rpx;font-weight:400;color:#1DC691;">创建</text> -->
                    <!-- <view @tap="openSt" class="st_btn" v-if="type!=='pick'&&VER.ver">声明与文献</view> -->
                </view>

            </view>
        </view>
        <view  class="content" style="top: calc(100rpx + var(--status-bar-height))" :style="{bottom:bottomHeight+'px'}">
            <!-- 顶部位置占位 -->
            <pullScroolView
                v-if="pageData.list?.length > 0"
                class="scr"
                ref="scroll"
                :back-top="false"
                :pullDown="refresh"
                :pullUp="scrolltolower"
            >
                <view class="scrool-view d-flex wrap j-between">
                    <view
                        v-for="item in pageData.list"
                        @tap="goProgrammDetails(item.id)"
                        class="scrool-cell selected"
                    >
                        <view
                            v-if="type !== 'pick' && item.inUse == 1"
                            class="in-use"
                            >使用中</view
                        >
                        <view class="page-view d-flex a-center j-center">
                            <view class="page-view-number">{{
                                item.pageView
                            }}</view>
                            <i
                                class="icon icon-zhanshifanwei"
                                style="
                                    font-size: 25rpx;
                                    color: #ffffff;
                                    line-height: 33;
                                "
                            ></i>
                        </view>
                        <image class="cell-img" :src="item.photo"></image>
                        <view class="cell-info d-flex a-center j-between">
                            <view class="info-name">{{ item.name }}</view>
                            <view class="yuanchuang d-flex a-center j-center" v-if="item.authorId===userData.id">
                                原创
                            </view>
                            <view class="zhuancun d-flex a-center j-center" v-if="item.authorId!==userData.id">
                                转存
                            </view>
                        </view>
                        <view class="cell-introduction">{{
                            formatIntroduction(item.introduction)
                        }}</view>
                        <view
                            v-if="type === 'pick'"
                            class="check_box"
                            @tap.stop="toggleCheck(item)"
                        >
                            <image
                                v-if="inGroup(item)"
                                class="checkImg"
                                style="width: 32rpx; height: 32rpx"
                                src="@/static/image/diet-menu-check-true.png"
                            ></image>
                            <image
                                v-else
                                class="checkImg"
                                style="width: 32rpx; height: 32rpx"
                                src="@/static/image/sports-menu-check-false.png"
                            ></image>
                        </view>
                        <view
                            v-if="type === 'pick' && inGroup(item)"
                            class="shadow"
                        ></view>
                    </view>
                </view>
            </pullScroolView>
        </view>

        <view class="bottom-btn d-flex d-c j-center" v-if="pageData.list?.length > 0">
                <tm-button
                    v-if="type!=='pick'"
                    _style="margin: 0;font-weight: 600;"
                    :width="690"
                    :height="80"
                    :shadow="-1"
                    round="5"
                    :linear-color="['#64F1C5', '#29DBA3']"
                    linear="left"
                    :fontSize="32"
                    fontColor="#ffffff"
                    label="创建方案"
                    @tap="goProgrammeCreate"
                ></tm-button>

                <tm-button
                    v-if="type==='pick'"
                    _style="margin: 0;font-weight: 600;"
                    :width="690"
                    :height="80"
                    :shadow="-1"
                    round="5"
                    :linear-color="['#64F1C5', '#29DBA3']"
                    linear="left"
                    :fontSize="32"
                    fontColor="#ffffff"
                    :label='`删除${newGroupPlan.length}个方案`'
                    @tap="submit"
                ></tm-button>

                <view class="heightBox"></view>
            </view>

        <view v-if="pageData.list?.length === 0" class="page-null d-flex d-c a-center j-center">
            <image
                mode="widthFix"
                style="width: 360rpx"
                src="/static/img/nodata.png"
            />
            <view class="page-null-text"
                >你还没有瘦身方案，请创建方案或去方案广场寻找适合自己的方案</view
            >
            <tm-button
                _style="margin: 160rpx 0 0 0;font-weight: 600;"
                :width="390"
                :height="80"
                :shadow="-1"
                round="5"
                :linear-color="['#64F1C5', '#29DBA3']"
                linear="left"
                :fontSize="32"
                fontColor="#ffffff"
                label="创建方案"
                @tap="goProgrammeCreate"
            ></tm-button>
            <tm-button
                @tap="goProgrammePublic"
                _style="margin: 40rpx 0 0 0;font-weight: 600;"
                :width="390"
                :height="80"
                :shadow="-1"
                round="5"
                :fontSize="32"
                color="#29DBA3"
                :outlined="true"
                fontColor="#29DBA3"
                label="去方案广场"
            ></tm-button>
        </view>
    </view>
    <statement ref="stPopup"></statement>
</template>

<script setup lang="tsx" name="programme">
import { userData as userDataStore } from "@/store/userData";
import { ref, computed } from "vue";
import { systemInfo as systemInfoStore } from "@/store/systemInfo";
import { onLoad, onShow } from "@dcloudio/uni-app";
import { getUserPlanList, getGroupPlan, editGroupPlan } from "@/api/api";
import statement from "@/components/statement.vue";
import { ver } from "@/store/ver";
const VER = ver();
const stPopup = ref(null);
const openSt = ()=>{
    stPopup.value.open();
}


const systemInfo = systemInfoStore();

const goProgrammePublic = () => {
	uni.navigateTo({
	    url: `/pages/programme/programmePublic`,
	});
}

const bottomHeight = computed(()=>{
    return systemInfo.safeAreaInsets?.bottom?(systemInfo.safeAreaInsets?.bottom+uni.upx2px(100)) : uni.upx2px(130)
})

const oldGroupPlan = ref([]);
const newGroupPlan = ref([]);

const type = ref("");
const groupId = ref("");

const titleText = computed(() => {
    if (type.value === "pick") {
        return "删除群方案";
    }
    return "我的方案";
});

const inGroup = computed(() => (item: any) => {
    return newGroupPlan.value.some((gPlan) => gPlan.id === item.id);
});

const toggleCheck = (item) => {
    const index = newGroupPlan.value.findIndex((g) => g.id === item.id);
    if (index === -1) {
        newGroupPlan.value.push(item);
    } else {
        newGroupPlan.value.splice(index, 1);
    }
};

const adds = () => {
    let arr = [];
    newGroupPlan.value.forEach((newItem) => {
        if (oldGroupPlan.value.every((oldItem) => oldItem.id !== newItem.id)) {
            arr.push(newItem);
        }
    });

    return arr;
};
const subs = () => {
    let arr = [];
    oldGroupPlan.value.forEach((oldItem) => {
        if (newGroupPlan.value.every((newItem) => newItem.id !== oldItem.id)) {
            arr.push(oldItem);
        }
    });
    return arr;
};

let loading = false;

const submit = async () => {

    if(!newGroupPlan.value.length){
        uni.showToast({
            icon: "none",
            title: "请选择要删除的方案",
            duration: 2000,
        });

        return;
    }

    if(loading){
        return;
    }

    loading = true;

    // let _adds = adds();
    // let _subs = subs();
    const params = {
        groupId: groupId.value,
        addPlanId: [],
        delPlanId: newGroupPlan.value.map((item) => item.id),
    };
    const res = await editGroupPlan(params).catch(()=>{
        loading = false;
    });

    const { flag } = res;
    if (flag !== 1) {
        uni.showToast({
            icon: "none",
            title: "删除群方案失败",
            duration: 2000,
        });
        loading = false;
        return;
    }


    

    setTimeout(()=>{
        uni.navigateBack({
            success(){

                uni.showToast({
                        icon: "success",
                        title: "已删除",
                        duration: 1500,
                });

            }
        });
    },100)


};

const goBack = () => {
    uni.navigateBack();
};
const userData: any = userDataStore();
let pageData: any = ref({});
let params: any = {
    userId: userData.id,
    //userId:10000013,
    page: 1,
    rows: 10,
};
//页面加载完成后加载初始数据
onLoad((option) => {
    if (option.groupId) {
        type.value = option.type;
        groupId.value = option.groupId;
        GetGroupPlan(option.groupId);
    }
});
onShow(() => {
    //refresh();
});

const GetGroupPlan = async (groupId: any) => {
    const params = {
        groupId,
    };
    const res = await getGroupPlan(params);
    console.log("GetGroupPlan");
    console.log("GetGroupPlan");
    console.log("GetGroupPlan");
    console.log(res);
    oldGroupPlan.value = JSON.parse(JSON.stringify(res.data.list));
    newGroupPlan.value = [];
    pageData.value = res.data;
};

const scroll = ref();
//下拉刷新数据
const refresh = () => {
    params.page = 1; //设置刷新时查询第一页
    getUserPlanList(params).then((res: any) => {
        if (res.success) {
            params.page++; //设置下一页
            pageData.value = res.data;
            setTimeout(() => {
                scroll.value.success();
            }, 500);
        }
    });
};
//下拉加载
const scrolltolower = () => {
    if (params.page >= pageData.value.pages) return;
    getUserPlanList(params).then((res: any) => {
        params.page++; //设置下一页
        pageData.value.list.push(...res.data.list);
    });
};
const goProgrammeCreate = () => {
    uni.navigateTo({
        url: `/pages/programmeCreate/programmeCreate`,
    });
};
const goProgrammDetails = (id: string) => {
    uni.navigateTo({
        url: `/pages/programmeDetails/programmeDetails?programmeId=${id}&from=group`,
    });
};
const formatIntroduction = (str: string) => {
    return str.replace(/\n/g, "").replace(/\s/g, "");
};
</script>

<style lang="scss" scoped>
@import "./programme.scss";
.content{
    position:fixed;
    left:0;
    right:0;
    .scr{
        flex:1;
    }
}
.heightBox {
        height: env(safe-area-inset-bottom);
        width:750rpx;
        min-height: 20rpx;
    }
.yuanchuang{
    background:#def2e5;
    color:#2ec593;
    font-size:26rpx;
    width:70rpx;
    height:40rpx;
    border-radius: 4rpx;
}
.zhuancun{
    background:#f9e6d6;
    color:#eb8d55;
    font-size:26rpx;
    width:70rpx;
    height:40rpx;
    border-radius: 4rpx;
}
</style>
